package com.probox.apiModules.controller.order;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.probox.common.core.enums.ProfitsharingAddTypeEnum;
import com.probox.common.core.web.controller.BaseController;
import com.probox.common.core.web.domain.AjaxResult;
import com.probox.common.entity.service.order.IOrderInfoParentService;
import com.probox.common.entity.service.order.IOrderInfoService;
import com.probox.order.api.domain.ProfitShareReceiver;
import com.probox.order.api.domain.ProfitShareVo;
import com.probox.order.api.utils.WechatV3Payment;
import io.swagger.annotations.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(value = "微信支付回调接口",tags = {"微信支付回调"})
@RestController
@RequestMapping("/order/openWechat")
public class OpenOrderWechatController extends BaseController {

    @Autowired
    private IOrderInfoService orderInfoService;

    @Autowired
    private IOrderInfoParentService orderInfoParentService;

    private static final Logger logger = LoggerFactory.getLogger(OpenOrderWechatController.class);

    /*
    {
        "id": "c9402fc7-2def-536f-9b60-4c99135ac2fa",
            "create_time": "2021-07-15T09:35:56+08:00",
            "resource_type": "encrypt-resource",
            "event_type": "TRANSACTION.SUCCESS",
            "summary": "支付成功",
            "resource": {
            "original_type": "transaction",
                    "algorithm": "AEAD_AES_256_GCM",
                    "ciphertext": "4kYv2njknJBMtfhw0Poth+TMR8eXbrJ33g2nZKUGIhg4BzRYP35iI/iyG7U7CHyEh2/taXzmxHqY/CA4MlQ8TggQ5k2LEHiJ/D3TuFOA3ACmL0DmkP8fL7H5AhZAOloC+wkHTLkYdVVRLQdXILnpe+cEZ0fvgQQnlXjLH7eqmFuZ1XjCPgtNPHKc6bQBTEttiqc+gb55Jy5mAbuI213WzSGEXsMSqHZQIaokL/WG0BkiLZnY0gKzffVSuwzi80R7mVcB7hEc190nciclU1JGYHOT7dgDZXOP/pymvja6HK9GryL/M6/oq6tD45VXQSsrjFGXZwXelY4Yabvrpp/sAQGDFkNFOTa+wrXOI6MVuF9EYyQPjFXAnodNkgGXIDEFWtRD4aN5FTPEQ8stDyVcANgVItULdDnz7rM2fFhVfgbyuUOrewjODPT7M4tpFo42a4+zYlWDdc7G1uIdB5z+0Ej+InEzJ7SbULE++UQHkAxj/uDuqVusCu6K0AeJBDfIIYnyuQBQjCwfR550cPY4ikh5qUroC9OkDgbpVHwDbrWhYPRJdPBG35PHe1Q3xyY0UUYvq3F0PR4X1whHVpsRHtEQwdsVV+OjokRwmbuTZnBFioX5dFujRC/ox6cu1aJr63L4LgIlpTWBbYAtOX0q6XjXtHc++gM1OLAoz7ebYoqtiH+QjqrvgAs4XHZ7ZLe9MDpwTFjRnwfELStRoZg=",
                    "associated_data": "transaction",
                    "nonce": "bw76rHoceLKU"
            }
    }
    */
    /**
     * 微信支付回调
     * @param request
     * @param response
     */
    @PostMapping(value = "/paymentCallBack")
    public void paymentCallBack(HttpServletRequest request, HttpServletResponse response){
        logger.info("============进入微信支付回调==============");
        Map<String, String> map = new HashMap<>(12);
        response.setHeader("Content-type", ContentType.JSON.toString());
        response.setStatus(500);
        map.put("code", "ERROR");
        map.put("message", "签名错误");
        try {
            String result = WechatV3Payment.readData(request);
            logger.info("\n===========微信支付回调原始内容：{}",result);
            // 需要通过证书序列号查找对应的证书，verifyNotify 中有验证证书的序列号
            String plainText = WechatV3Payment.verifyNotify(result);
            logger.info("\n===========微信支付回调解密内容：{}",plainText);
            if (StrUtil.isNotEmpty(plainText)) {
                if (orderInfoService.wechatPaymentCallBack(JSON.parseObject(plainText))) {
                    response.setStatus(200);
                    map.put("code", "SUCCESS");
                    map.put("message", "SUCCESS");
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        String rst = JSONUtil.toJsonStr(map);
        try {
            response.getOutputStream().write(rst.getBytes(StandardCharsets.UTF_8));
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
        }
        logger.info("\n============完成微信支付回调，结果:{}==============",rst);
    }
}
